package com.mall.order.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.order.OrderCoreService;
import com.mall.order.biz.TransOutboundInvoker;
import com.mall.order.biz.context.AbsTransHandlerContext;
import com.mall.order.biz.factory.OrderProcessPipelineFactory;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.converter.OrderConverter;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.OrderShipping;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * cskaoyan
 */
@Slf4j
@Component
@Service(cluster = "failfast")
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;

    @Autowired
    OrderConverter converter;


    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Override
    public CreateOrderResponse createOrder(CreateOrderRequest request) {
        CreateOrderResponse response = new CreateOrderResponse();
        try {
            //创建pipeline对象
            TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

            //启动pipeline
            invoker.start(); //启动流程（pipeline来处理）

            //获取处理结果
            AbsTransHandlerContext context = invoker.getContext();

            //把处理结果转换为response
            response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);
        } catch (Exception e) {
            log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    /**
     * @param request
     * @return com.mall.order.dto.OrderListResponse
     * @description 获取当前用户所有订单的具体实现
     * @author ghr
     * @date 2022/1/20 2:04 下午
     */
    @Override
    public OrderListResponse orderList(OrderListRequest request) {
//        OrderListResponse response = new OrderListResponse();
//        try {
//            request.requestCheck();
//            Example example = new Example(Order.class);
//            if (request.getSort() != null) {
//                example.setOrderByClause(request.getSort());
//            }
//            Example.Criteria criteria = example.createCriteria();
//            criteria.andEqualTo("userId", request.getUserId());
//            List<Order> orders = orderMapper.selectByExample(example);
//            List<OrderDetailInfo> detailInfoList = response.getDetailInfoList();
//            detailInfoList = new ArrayList<OrderDetailInfo>();
//            for (Order order : orders) {
//                detailInfoList.add(converter.order2detail(order));
//            }
//            for (OrderDetailInfo orderDetailInfo : detailInfoList) {
//                String orderId = orderDetailInfo.getOrderId();
//                Example example1 = new Example(OrderItem.class);
//                Example.Criteria criteria1 = example1.createCriteria();
//                criteria1.andEqualTo("orderId", orderId);
//                List<OrderItem> orderItems = orderItemMapper.selectByExample(example1);
//                List<OrderItemDto> orderItemDtos = converter.item2dto(orderItems);
//                orderDetailInfo.setOrderItemDto(orderItemDtos);
//
//                Example example2 = new Example(OrderShipping.class);
//                Example.Criteria criteria2 = example2.createCriteria();
//                criteria2.andEqualTo("orderId", orderId);
//                List<OrderShipping> orderShippings = orderShippingMapper.selectByExample(example2);
//                OrderShippingDto orderShippingDto = converter.shipping2dto(orderShippings.get(0));
//                orderDetailInfo.setOrderShippingDto(orderShippingDto);
//            }
//            PageHelper.startPage(request.getPage(), request.getSize());
//            PageInfo<OrderDetailInfo> pageInfo = new PageInfo<>(detailInfoList);
//            long total = pageInfo.getTotal();
//            response.setDetailInfoList(detailInfoList);
//            response.setTotal(total);
//            response.setCode(OrderRetCode.SUCCESS.getCode());
//            response.setMsg(OrderRetCode.SUCCESS.getMessage());
//        } catch (Exception e) {
//            log.error("OrderCoreServiceImpl.orderList occur Exception :" + e);
//            ExceptionProcessorUtils.wrapperHandlerException(response, e);
//        }
//        return response;



        request.requestCheck();

        OrderListResponse orderListResponse = new OrderListResponse();
        orderListResponse.setCode(OrderRetCode.SUCCESS.getCode());
        orderListResponse.setMsg(OrderRetCode.SUCCESS.getMessage());

        PageHelper.startPage(request.getPage(),request.getSize());

        Example example = new Example(Order.class);
        example.setOrderByClause("create_time desc");
        example.createCriteria().andEqualTo("userId", request.getUserId());
        List<Order> orderList = orderMapper.selectByExample(example);
        PageInfo<Order> orderPageInfo = new PageInfo<>(orderList);
        long total = orderPageInfo.getTotal();
        if(CollectionUtils.isEmpty(orderList)){
            orderListResponse.setTotal(0L);
            orderListResponse.setDetailInfoList(new ArrayList<>());
            return orderListResponse;
        }

        List<OrderDetailInfo> infos = new ArrayList<>();
//        orderListResponse.setTotal((long)orderList.size());
        try {
            orderList.stream().forEach(order -> {
                OrderDetailInfo orderDetailInfo = getOrderDetailInfo(order);
                infos.add(orderDetailInfo);
            });

        } catch (Exception e) {
            log.info("OrderQueryServiceImpl.orderList occur Exception: {}" , e);
            ExceptionProcessorUtils.wrapperHandlerException(orderListResponse, e);
        }

        orderListResponse.setTotal(total);
        orderListResponse.setDetailInfoList(infos);
        return orderListResponse;
    }
    private OrderDetailInfo getOrderDetailInfo(Order order) {
        OrderDetailInfo orderDetailInfo = converter.order2detail(order);


        List<OrderItem> orderItems = orderItemMapper.queryByOrderId(order.getOrderId());
        List<OrderItemDto> orderItemDtos = converter.item2dto(orderItems);
        orderDetailInfo.setOrderItemDto(orderItemDtos);

        OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(order.getOrderId());
        OrderShippingDto orderShippingDto = converter.shipping2dto(orderShipping);
        orderDetailInfo.setOrderShippingDto(orderShippingDto);
        return orderDetailInfo;
    }

    /**
     * @param request
     * @return com.mall.order.dto.OrderDetailResponse
     * @description 查询订单详情的具体实现方法
     * @author ghr
     * @date 2022/1/20 6:13 下午
     */
    @Override
    public OrderDetailResponse orderDetail(OrderDetailRequest request) {
        OrderDetailResponse response = new OrderDetailResponse();

        try {
            request.requestCheck();
            String orderId = request.getOrderId();
            Order order = orderMapper.selectByPrimaryKey(orderId);
            Long userId = order.getUserId();
            Integer orderStatus = order.getStatus();
            BigDecimal orderTotal = order.getPayment();
            response.setUserId(userId.intValue());
            response.setOrderStatus(orderStatus);
            response.setOrderTotal(orderTotal);

            OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(orderId);
            String userName = orderShipping.getReceiverName();
            String tel = orderShipping.getReceiverPhone();
            String streetName = orderShipping.getReceiverAddress();
            response.setUserName(userName);
            response.setTel(tel);
            response.setStreetName(streetName);

            Example itemExample = new Example(OrderItem.class);
            Example.Criteria criteria = itemExample.createCriteria();
            criteria.andEqualTo("orderId", orderId);
            List<OrderItem> orderItems = orderItemMapper.selectByExample(itemExample);
            List<OrderItemDto> orderItemDtos = converter.item2dto(orderItems);
            response.setGoodsList(orderItemDtos);
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("OrderCoreServiceImpl.orderDetail occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    /**
     * @param request
     * @return com.mall.order.dto.CancelOrderResponse
     * @description 取消订单具体实现
     * @author ghr
     * @date 2022/1/20 7:25 下午
     */
    @Override
    public CancelOrderResponse cancelOrder(CancelOrderRequest request) {
        CancelOrderResponse response = new CancelOrderResponse();
        try {
            request.requestCheck();
            String orderId = request.getOrderId();
            Order order = new Order();
            order.setOrderId(orderId);
            order.setStatus(7);
            order.setCloseTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
            orderItemMapper.updateStockStatus(2,orderId);
            Example example = new Example(OrderItem.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("orderId",orderId);
            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
            for (OrderItem orderItem : orderItems) {
                Long itemId = orderItem.getItemId();
                Integer num = orderItem.getNum();
                Stock stock = new Stock();
                stock.setItemId(itemId);
                stock.setLockCount(-num);
                stock.setStockCount(Long.parseLong(num.toString()));
                stockMapper.updateStock(stock);
            }
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("OrderCoreServiceImpl.cancelOrder occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    /**
     * @description 删除订单的具体实现
     * @author ghr
     * @date 2022/1/20 7:42 下午
     * @param
     * @param request
     * @return com.mall.order.dto.DeleteOrderResponse
     */
    @Override
    public DeleteOrderResponse deleteOrder(DeleteOrderRequest request) {
        DeleteOrderResponse response = new DeleteOrderResponse();

        try {
            request.requestCheck();
            String orderId = request.getOrderId();
            orderMapper.deleteByPrimaryKey(orderId);

            Example example = new Example(OrderItem.class);
            example.createCriteria().andEqualTo("orderId", orderId);
            orderItemMapper.deleteByExample(example);

            orderShippingMapper.deleteByPrimaryKey(orderId);
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            log.error("OrderCoreServiceImpl.deleteOrder occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    /**
     * @description 支付成功时，更新订单状态，更新锁定库存
     * @author ghr
     * @date 2022/1/26 3:39 下午
     * @param request
     * @return com.mall.order.dto.PayOrderSuccessResponse
     */
    @Override
    public PayOrderSuccessResponse payOrderSuccess(PayOrderSuccessRequest request) {
        PayOrderSuccessResponse response = new PayOrderSuccessResponse();

        request.requestCheck();
        String orderId = request.getOrderId();
        Order order = new Order();
        order.setOrderId(orderId);
        order.setPaymentType(1);
        order.setStatus(1);
        order.setUpdateTime(new Date());
        order.setPaymentTime(new Date());
        orderMapper.updateByPrimaryKeySelective(order);

        Example example = new Example(OrderItem.class);
        example.createCriteria().andEqualTo("orderId",orderId);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
        for (OrderItem orderItem : orderItems) {
            Long itemId = orderItem.getItemId();
            Integer num = orderItem.getNum();
            Stock stock = new Stock();
            stock.setItemId(itemId);
            stock.setLockCount(-num);
            stock.setStockCount(0L);
            stockMapper.updateStock(stock);
        }
        response.setMsg("更新订单状态，更新锁定库存");
        return response;
    }
}
